﻿using System;
using System.ComponentModel;
using System.Windows.Forms;


namespace DuinoWebserver.Windows
{
    public partial class Form1 : Form
    {
        private Application _application = new Application();

        public Form1()
        {
            InitializeComponent();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            // do something useful
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            backgroundWorker1.CancelAsync();

            while (_application != null)
                System.Windows.Forms.Application.DoEvents();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync(_application);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var application = e.Argument as Application;
            application.Init();
            while (!worker.CancellationPending)
            {
                application.Loop();
                worker.ReportProgress(0, application);
            }
            e.Cancel = true;
            e.Result = application;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            var application = e.UserState as Application;
            this.cbxOnboardLed.Checked = application.Led.StateInternal;
            application.Switch.StateInternal = this.cbxOnboardSw1.Checked;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _application.Dispose();
            _application = null;

            if (e.Cancelled)
                this.Text = "RunWorker Cancelled";

            else if (e.Error != null)
                this.Text = e.Error.Message;
        }
    }
}
